﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

using sgsBase;

namespace gaClear
{
	public class CPCInterface
	{
		protected string _url = "";
		protected string _msg = "";
		protected string _reply = "";
		protected string _sessCookie = "";

		public string Url
		{
			get 
			{
				if (_url == "")
					_url = ApplicationHelper.CfgGetAppSetting("CMEAPIUrl");
				return _url; 
			}
			set { _url = value; }
		}
		public string Message
		{
			get { return _msg; }
			set { _msg = value; }
		}
		public string ReplyMsg
		{
			get { return _reply; }
		}

		public XmlDocument ReplyXml
		{
			get
			{
				XmlDocument sxml = new XmlDocument();
				sxml.LoadXml(_reply);
				return sxml;
			}

		}

		public CPCInterface()
		{
			_url = ApplicationHelper.CfgGetAppSetting("CMEAPIUrl");
		}

		public void Reset()
		{
			_msg = "";
			_reply = "";
		}

		public bool SendMessage()
		{
			XmlDocument sxml = new XmlDocument();
			sxml.LoadXml(_msg);
			_reply = submitDoc(sxml);

			if (_reply == "") // if blank, try again
			{
				_reply = submitDoc(sxml);
				if (_reply == "")
					return false;
			}

			return true;
		}

		private string submitDoc(XmlDocument xdoc)
		{
			try
			{
				Byte[] bdata = System.Text.Encoding.UTF8.GetBytes(xdoc.OuterXml);
				Byte[] bresp;
				//FrmMain.CMEWebClient.Headers.Add("Content-Type", "text/xml");
				if (_sessCookie != "")
					FrmMain.CMEWebClient.Headers.Add("Cookie", _sessCookie);
				bresp = FrmMain.CMEWebClient.UploadData(Url, bdata);

				string resp = System.Text.Encoding.UTF8.GetString(bresp);
				if (FrmMain.CMEWebClient.ResponseHeaders["Set-Cookie"] != null)
					_sessCookie = FrmMain.CMEWebClient.ResponseHeaders["Set-Cookie"];
				return resp;
			}
			catch (Exception ex)
			{
				Email.SendError(ex);
			}
			return "";
		}
	}
}
